package com.quick.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quick.mapper.SysMenuMapper;
import com.quick.mapper.SysRoleMenuMapper;
import com.quick.service.ISysRoleMenuService;
import com.quick.sys.domain.pojo.SysMenu;
import com.quick.sys.domain.pojo.SysRoleMenu;
import com.quick.util.QuickTool;

import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class SysRoleMenuServiceImpl implements ISysRoleMenuService{
	
	private final SysRoleMenuMapper roleMenuMapper;
	private final SysMenuMapper menuMapper;

	@Override
	public void saveRoleMenu(List<Integer> menuIds, Integer roleId) {
		if(QuickTool.notNull(menuIds)) {
			QueryWrapper<SysMenu> menuQueryWrapper = new QueryWrapper<SysMenu>();
			menuQueryWrapper.lambda().select(SysMenu::getParentId);
			menuQueryWrapper.lambda().in(SysMenu::getId, menuIds);
			menuQueryWrapper.lambda().notIn(SysMenu::getParentId, -1);
			menuQueryWrapper.lambda().groupBy(SysMenu::getParentId);
			List<SysMenu> menus = menuMapper.selectList(menuQueryWrapper);
			for (SysMenu m : menus) {
				menuIds.add(m.getParentId());
			}
			QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<SysRoleMenu>();
			queryWrapper.lambda().eq(SysRoleMenu::getRoleId, roleId);
			roleMenuMapper.delete(queryWrapper);
			for (Integer menu : menuIds) {
				SysRoleMenu entity = new SysRoleMenu();
				entity.setMenuId(menu);
				entity.setRoleId(roleId);
				QuickTool.setFillInsert(entity);
				roleMenuMapper.insert(entity);
			}
		}
		
	}

	@Override
	public List<Integer> selectMenuByRoles(List<Integer> roles) {
		QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<SysRoleMenu>();
		queryWrapper.lambda().in(SysRoleMenu::getRoleId, roles);
		List<SysRoleMenu> menus = roleMenuMapper.selectList(queryWrapper);
		return menus.stream().map(e->e.getMenuId()).collect(Collectors.toList());
	}

}
